package org.obsidianrad.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * 
 * @author Eligio Colutta
 * @version $Rev: 4 $
 * @lastautorcommit $Author: eliosh $
 * @lastdatecommit $Date: 2009-10-31 12:37:28 +0100(sab, 31 ott 2009) $
 */
public class ObjectSerializer {

	public static byte[] serialize(Serializable object, boolean compressed) throws IOException{
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(object);
		
		byte[] objByteArray = baos.toByteArray();
		byte[] output;
		
		if(compressed){
			// Compress the bytes
			output = new byte[objByteArray.length];
			Deflater compresser = new Deflater();
			compresser.setInput(objByteArray);
			compresser.finish();
			compresser.deflate(output);
		}else{
			output = objByteArray;
		}
		
		return output;
	}

	public static Object unserialize(byte[] content, boolean compressed) throws DataFormatException, IOException, ClassNotFoundException{
		Object retval = null;
		if(compressed){
			Inflater decompresser = new Inflater();
			decompresser.setInput(content);
			byte[] result = new byte[content.length];

			decompresser.inflate(result);
			decompresser.end();
			ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(result));
			retval = objectIn.readObject();		
		}else{
			ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(content));
			retval = objectIn.readObject();
		}
		return retval;
	}
}
